# -*- coding: utf-8 -*-
# @Time    : 2022/10/28 14:32
# @Author  : 限量老
import json

from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from app01 import models
from app01.utils.form_总 import TaskModelForm
from app01.utils.pagination分页组件 import Pagination


def task_list(request):
    '''任务列表'''

    # 去数据库获取所有的任务
    queryset = models.Task.objects.all().order_by('-id')

    # 分页:
    page_object = Pagination(request, queryset)  # 生成分页对象        #分页须加

    form = TaskModelForm()
    context = {
        'form': form,
        # 'queryset':queryset,
        'queryset': page_object.page_queryset,  # 分页完的数据       #分页须加
        'page_string': page_object.html()  # 生成页码               #分页须加
    }
    return render(request, 'task_list.html', context)


@csrf_exempt  # post请求免除csrf验证
def task_ajax(request):
    print('GET请求:', request.GET)
    print('POST请求:', request.POST)

    data_dict = {'status': True, 'data': [11, 22, 33, 44]}
    # dumps是将dict转化成str格式，loads是将str转化成dict格式
    return HttpResponse(json.dumps(data_dict))
    # return JsonResponse(data_dict)#跟上面等同，直接返回字典内容，自己内部转换


@csrf_exempt  # post请求免除csrf验证
def task_add(request):
    print(request.POST)

    # 1.用户发送过来的数据进行校验
    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {'status': True}
        return HttpResponse(json.dumps(data_dict))

    data_dict = {'status': False, 'error': form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
